package com.morehair.service.admin.impl;

import com.aliyun.oss.model.PutObjectResult;
import com.morehair.bean.pojo.Storage;
import com.morehair.config.component.AliyunComponent;
import com.morehair.mapper.StorageMapper;
import com.morehair.service.admin.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: DLX
 * @Date: 2021/6/7 15:03
 * @Description:
 **/

@Service
@Transactional
public class FileServiceImpl implements FileService {

    @Autowired
    AliyunComponent aliyunComponent;
    @Autowired
    StorageMapper storageMapper;

    @Override
    public Storage fileUpload(MultipartFile multipartFile) throws IOException, ParseException {
//        if (file.) {
//            判断图片类型
//            return BaseRespVo.fail();
//        }
        String key = UUID.randomUUID().toString().replace("-", "");
        String fileName = key + multipartFile.getOriginalFilename();
        String type = multipartFile.getContentType();
        Integer size = ((int) multipartFile.getSize());
        String url = "https://" + aliyunComponent.getOss().getBucket() + "." + aliyunComponent.getOss().getEndPoint() + "/" + fileName;
        InputStream inputStream = multipartFile.getInputStream();
        PutObjectResult putObjectResult = aliyunComponent.fileUpload(fileName, inputStream);

        Date date = new Date();
        Date addTime = date;
        Date updateTime = date;

        Storage storage = new Storage(null,key,fileName,type,size,url,addTime,updateTime,null);
        storageMapper.insertSelective(storage);
        Storage newStorage = storageMapper.query();

        return newStorage;
    }

    @Override
    public Storage updateStorage(Storage storage) {
        storageMapper.updateByPrimaryKeySelective(storage);
        return storage;
    }

    @Override
    public void deleteStorage(Storage storage) {
        storage.setDeleted(true);
        storageMapper.updateByPrimaryKeySelective(storage);
    }
}
